package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.dao.OrderItemDao;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import com.atguigu.gulimall.order.enums.OrderStatusEnum;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WareFeignService;
import com.atguigu.gulimall.order.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.PaymentInfoService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.to.SpuInfoTo;
import com.atguigu.gulimall.order.to.WareSkuLockTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    private ThreadLocal<OrderSubmitVo> orderSubmitTL = new ThreadLocal<>();

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    PaymentInfoService paymentInfoService;

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Qualifier("threadPoolExecutor")
    @Autowired
    Executor executor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberRespVo member = LoginUserInterceptor.loginUser.get();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> getAddresses = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> memberAddresses = memberFeignService.getMemberAddresses(member.getId());
            confirmVo.setAddress(memberAddresses);
        }, executor);

        CompletableFuture<Void> getItems = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> items = cartFeignService.getCurrentUserCartItems();
            confirmVo.setItems(items);
        }, executor).thenRunAsync(()->{
            List<Long> skuIds = confirmVo.getItems().stream().map(i -> i.getSkuId()).collect(Collectors.toList());
            R r = wareFeignService.getSkuHasStok(skuIds);
            if (r.getCode() == 0){
                List<SkuHasStockVo> skuHasStocks = r.getData(new TypeReference<List<SkuHasStockVo>>() {});
                Map<Long, Boolean> stocks = skuHasStocks.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
                confirmVo.setStocks(stocks);
            }
        },executor);

        confirmVo.setIntegration(member.getIntegration());

        String token = UUID.randomUUID().toString().replace("-","");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+member.getId(),token,30, TimeUnit.MINUTES);

        confirmVo.setOrderToken(token);

        CompletableFuture.allOf(getAddresses,getItems).get();
        return confirmVo;
    }

    //@GlobalTransactional
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo orderSubmitVo) {
        orderSubmitTL.set(orderSubmitVo);
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        responseVo.setCode(-1);
        MemberRespVo member = LoginUserInterceptor.loginUser.get();
        //1. 验令牌
        String pageToken = orderSubmitVo.getOrderToken();
        String script = "if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        RedisScript<Long> redisScript = new DefaultRedisScript(script,Long.class);
        Long checkRes = redisTemplate.execute(redisScript, Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + member.getId()), pageToken);
        if (checkRes == 0L){
            responseVo.setCode(1);
            return responseVo;
        }else {
            //创建订单 订单项
            OrderCreateTo orderCreateTo = createOrder();
            //验价格
            BigDecimal payAmount = orderCreateTo.getOrder().getPayAmount();
            BigDecimal payPrice = orderSubmitVo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue())<0.01){
                //保存订单
                saveOrderAndItems(orderCreateTo);
                //锁定库存 只要有异常 抛出 回滚

                WareSkuLockTo wareSkuLockTo = new WareSkuLockTo();
                wareSkuLockTo.setOrderSn(orderCreateTo.getOrder().getOrderSn());
                List<OrderItemVo> locks = orderCreateTo.getOrderItems().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                wareSkuLockTo.setLocks(locks);
                R r = wareFeignService.orderLockStock(wareSkuLockTo);
                if (r.getCode() == 0) {
                    //锁定成功
                    responseVo.setCode(0);
                    responseVo.setOrder(orderCreateTo.getOrder());
                    //int i = 1/0;
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",orderCreateTo.getOrder());
                    return responseVo;
                }else {
                    //锁定失败
                    responseVo.setCode(3);
                    return responseVo;
                }
            }else {
                responseVo.setCode(2);//验价失败
                return responseVo;
            }

        }
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        return this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn",orderSn));
    }



    @Transactional
    @Override
    public void closeOrder(OrderEntity order) {
        OrderEntity orderEntity = this.getById(order.getId());
        if (orderEntity!=null && orderEntity.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()){
            OrderEntity updateEntity = new OrderEntity();
            updateEntity.setId(order.getId());
            updateEntity.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(updateEntity);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity,orderTo);
            rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderTo);
        }
    }

    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        payVo.setOut_trade_no(orderSn);
        OrderEntity order = this.getOrderByOrderSn(orderSn);
        BigDecimal bigDecimal = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(bigDecimal.toString());
        List<OrderItemEntity> items = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity orderItemEntity = items.get(0);
        payVo.setSubject(orderItemEntity.getSkuName());
        payVo.setBody(orderItemEntity.getSkuAttrsVals());
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        QueryWrapper<OrderEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_id",memberRespVo.getId()).orderByDesc("id");
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                queryWrapper
        );
        List<OrderEntity> records = page.getRecords();
        if (records!=null){
            List<OrderEntity> orderEntities = records.stream().map(order -> {
                List<OrderItemEntity> items = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
                order.setItemEntities(items);
                return order;
            }).collect(Collectors.toList());
            page.setRecords(orderEntities);
        }
        return new PageUtils(page);
    }

    @Transactional
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        PaymentInfoEntity paymentInfo = new PaymentInfoEntity();
        paymentInfo.setAlipayTradeNo(vo.getTrade_no());
        paymentInfo.setOrderSn(vo.getOut_trade_no());
        paymentInfo.setPaymentStatus(vo.getTrade_status());
        paymentInfo.setCallbackTime(vo.getNotify_time());
        paymentInfoService.save(paymentInfo);
        if (vo.getTrade_status().equals("TRADE_SUCCESS")||vo.getTrade_status().equals("TRADE_FINISHED")) {
            String outTradeNo = vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(outTradeNo,OrderStatusEnum.PAYED.getCode());

        }
        return "success";
    }

    @Override
    public void createSeckillOrder(SeckillOrderTo to) {
        //TODO 保存订单
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(to.getOrderSn());
        orderEntity.setMemberId(to.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal multiply = to.getSeckillPrice().multiply(new BigDecimal(to.getNum()));
        orderEntity.setPayAmount(multiply);
        this.save(orderEntity);

        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(to.getOrderSn());
        orderItemEntity.setRealAmount(to.getSeckillPrice());
        orderItemEntity.setSkuQuantity(to.getNum());
        orderItemService.save(orderItemEntity);
    }

    private void saveOrderAndItems(OrderCreateTo orderCreateTo) {
        this.save(orderCreateTo.getOrder());
        orderItemService.saveBatch(orderCreateTo.getOrderItems());
    }

    private OrderCreateTo createOrder() {
        OrderCreateTo createTo = new OrderCreateTo();
        //创建订单号
        String orderSn = IdWorker.getTimeId();
        //创建订单
        OrderEntity orderEntity = buildOrder(orderSn);
        createTo.setOrder(orderEntity);

        //创建订单项buildOrderItems()
        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderSn);
        createTo.setOrderItems(orderItemEntities);

        //计算价格相关
        computePrice(orderEntity,orderItemEntities);

        return createTo;
    }

    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        BigDecimal total = new BigDecimal("0");
        BigDecimal coupon = new BigDecimal("0");
        BigDecimal integration = new BigDecimal("0");
        BigDecimal promotion = new BigDecimal("0");
        Integer giftGrowth = new Integer(0);
        Integer giftIntegration = new Integer(0);
        for (OrderItemEntity item : orderItemEntities) {
            BigDecimal realAmount = item.getRealAmount();
            total= total.add(realAmount);
            coupon = coupon.add(item.getCouponAmount()) ;
            integration = integration.add(item.getIntegrationAmount()) ;
            promotion = promotion.add(item.getPromotionAmount());
            giftGrowth += item.getGiftGrowth();
            giftIntegration += item.getGiftIntegration();
        }
        orderEntity.setTotalAmount(total);
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setCouponAmount(coupon);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegration(giftIntegration);
        orderEntity.setGrowth(giftGrowth);

        orderEntity.setDeleteStatus(0);//未删除
        orderEntity.setConfirmStatus(0);//未确认收货
        orderEntity.setCreateTime(new Date());
    }

    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        List<OrderItemVo> items = cartFeignService.getCurrentUserCartItems();
        if (items!=null&&items.size()>0){
            List<OrderItemEntity> collect = items.stream().map(i -> {
                OrderItemEntity orderItemEntity = buildOrderItem(i);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    private OrderEntity buildOrder(String orderSn) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        //用户
        MemberRespVo member = LoginUserInterceptor.loginUser.get();
        orderEntity.setMemberId(member.getId());
        orderEntity.setMemberUsername(member.getUsername());
        //获取收货地址信息
        OrderSubmitVo orderSubmitVo = orderSubmitTL.get();
        R r = wareFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo fareVo = r.getData(new TypeReference<FareVo>() {});
        //运费
        orderEntity.setFreightAmount(fareVo.getFare());
        //收货信息
        MemberAddressVo address = fareVo.getAddress();
        orderEntity.setReceiverCity(address.getCity());
        orderEntity.setReceiverDetailAddress(address.getDetailAddress());
        orderEntity.setReceiverName(address.getName());
        orderEntity.setReceiverPhone(address.getPhone());
        orderEntity.setReceiverPostCode(address.getPostCode());
        orderEntity.setReceiverRegion(address.getRegion());
        orderEntity.setReceiverProvince(address.getProvince());

        orderEntity.setAutoConfirmDay(7);
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());


        return orderEntity;
    }

    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setSkuId(cartItem.getSkuId());
        orderItemEntity.setSkuName(cartItem.getTitle());
        orderItemEntity.setSkuPic(cartItem.getImage());
        orderItemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(),";");
        orderItemEntity.setSkuAttrsVals(skuAttr);
        orderItemEntity.setSkuQuantity(cartItem.getCount());
        orderItemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        orderItemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());

        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoTo spuInfoTo = r.getData(new TypeReference<SpuInfoTo>() {});
        orderItemEntity.setSpuId(spuInfoTo.getId());
        orderItemEntity.setSpuName(spuInfoTo.getSpuName());
        orderItemEntity.setSpuBrand(spuInfoTo.getBrandId().toString());
        orderItemEntity.setCategoryId(spuInfoTo.getCatalogId());

        orderItemEntity.setCouponAmount(new BigDecimal("0"));
        orderItemEntity.setIntegrationAmount(new BigDecimal("0"));
        orderItemEntity.setPromotionAmount(new BigDecimal("0"));
        BigDecimal orign = cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString()));
        BigDecimal realAmount = orign.subtract(orderItemEntity.getCouponAmount())
                                    .subtract(orderItemEntity.getIntegrationAmount())
                                    .subtract(orderItemEntity.getPromotionAmount());
        orderItemEntity.setRealAmount(realAmount);
        return orderItemEntity;
    }

}